﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Jinjia.Approve.IRepository;
using Jinjia.Approve.IRepository.JJFlow;
using Jinjia.Approve.IService.JJFlow.Approvers;

namespace Jinjia.Approve.Service.JJFlow.Approvers
{
    public class CSpplyPiceAproveRealize : IJJApprovers
    {
        private readonly IJJApproversRepository _jjApproversRepository;
        private readonly IErpaBaseRepository _erpaBaseRepository;

        public CSpplyPiceAproveRealize(IJJApproversRepository jjApproversRepository, IErpaBaseRepository erpaBaseRepository)
        {
            _jjApproversRepository = jjApproversRepository;
            _erpaBaseRepository = erpaBaseRepository;
        }

        public async Task<List<int>> GetInstanceNodeEmpInfo(string biz_order_id, int start_user = 0, string depart_id = "0", Dictionary<string, string> dic = null)
        {
            var list_user_id = await _jjApproversRepository.GetBrandLeader(biz_order_id);
            //获取品牌编码
            var list_brand_code = list_user_id.Select(x => x.brand_code).ToList();
            //获取品牌成品采购人id
            var list_leader_id = list_user_id.Where(x => x.purchase_user_id > 0).Select(x => x.purchase_user_id).ToList();

            //品牌数量和品牌成品采购人应该是一对一，不一致则说明有无品牌负责人的品牌,所有无品牌成品采购人的品牌默认负责人为邢圆圆
            if (list_brand_code.Count != list_leader_id.Count)
            {
                list_leader_id.Add(await GetDefaultApprover());
            }

            //存在多品牌负责人是同一个人的情况，故去重
            var new_list_leader_id = list_leader_id.Distinct().ToList();

            return new_list_leader_id;
        }

        /// <summary>
        /// 获取默认审批人
        /// </summary>
        /// <returns></returns>
        private async Task<int> GetDefaultApprover()
        {
            var query = await _erpaBaseRepository.GetModelByCodeType("CSpplyPiceApplyDefaultApprover", "1");
            var approver_id = 0;
            if (query != null)
            {
                approver_id = Convert.ToInt32(query.value);
            }

            return approver_id;
        }
    }
}